package com.sl.au.controller;

import com.sl.au.entity.*;
import com.sl.au.service.AaccountsReceivableAccorspandingContractService;
import com.sl.au.service.AccountsReceivablePlanService;
import com.sl.au.service.AccountsReceivableTypeService;
import com.sl.au.service.ContractService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.PayPlanService;
import com.sl.au.service.PaymentInitialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 应收账管理控制器
 */
@RestController
@RequestMapping(value="/ui/paySchedule")
public class PaymentScheduleController extends BaseController {
    @Autowired
    ContractService contractService;
    @Autowired
    PaymentInitialService paymentInitialService;
    @Autowired
    PayPlanService payPlanService;
    @Autowired
    OperateLogService operateLogService;
    @Autowired
    AccountsReceivableTypeService accountsReceivableTypeService;
    @Autowired
    AccountsReceivablePlanService accountsReceivablePlanService;
    @Autowired
    AaccountsReceivableAccorspandingContractService aaccountsReceivableAccorspandingContractService;

    /**
     * 应收账计划页面显示
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index1() {
        Module module = this.getPageModule("paySchedule");
        ModelAndView modelAndView = createLayoutView("payment/payScheduleindex");
        modelAndView.addObject("module", module);
        List<AccountsReceivableType> a = accountsReceivableTypeService.getRepository().findAllByNAccountsReceivableTypeOrder();
        modelAndView.addObject("accountsReceivableTypes", a);
        return modelAndView;
    }

    /**
     * 应收账初始化页面显示
     * @param contractId
     * @param contractType
     * @return
     */
    @RequestMapping(value = "/paymentInitial/{contractId}/{contractType}", method = RequestMethod.GET)
    public ModelAndView paymentInitial(@PathVariable String contractId,
                                       @PathVariable String contractType) {
        ModelAndView modelAndView = createLayoutView("payment/paymentInitial");
        Account a = this.getMyAccount();
        User user = a.getUser();
        if (contractType.equals("备件合同")) {
            ContractPart contractPart = null;
            if (contractId != null && !contractId.equals("")) {
                contractPart = contractService.getContractPartById(contractId);
                //paymentInitialService.getPaySchedule(contractId,contractType);
                //payPlanService.payNotionalPooling(contractId,user.getName());
                 }
                modelAndView.addObject("contract", contractPart);
            } else if (contractType.equals("备泵合同")) {
                ContractPump contractPump = null;
                if (contractId != null && !contractId.equals("")) {
                    contractPump = contractService.getContractPumpById(contractId);
                    //paymentInitialService.getPaySchedule(contractId,contractType);
                    //payPlanService.payNotionalPooling(contractId,user.getName());
                }
                modelAndView.addObject("contract", contractPump);
            } else if (contractType.equals("维修合同")) {
                ContractRepair contractRepair = null;
                if (contractId != null && !contractId.equals("")) {
                    contractRepair = contractService.getContractRepairById(contractId);
                    //paymentInitialService.getPaySchedule(contractId,contractType);
                    //payPlanService.payNotionalPooling(contractId,user.getName());
                }
                modelAndView.addObject("contract", contractRepair);
            } else {
                Contract contract = null;
                if (contractId != null && !contractId.equals("")) {
                    contract = contractService.getContractById(contractId);
                    //paymentInitialService.getPaySchedule(contractId,contractType);
                    //payPlanService.payNotionalPooling(contractId,user.getName());
                    
                }
                modelAndView.addObject("contract", contract);
            }
        List<AccountsReceivableType> accountsReceivableTypes = accountsReceivableTypeService.getRepository().findAllByNAccountsReceivableTypeOrder();
        modelAndView.addObject("accountsReceivableTypes", accountsReceivableTypes);
        return modelAndView;
    }
    /**
     *  应收账计划表
     * @param contractId
     * @param contractType
     * @return
     */
        @RequestMapping(value = "/{contractId}/{contractType}/getData", method = RequestMethod.GET)
        public Map<String, Object> getData (@PathVariable String contractId,
                                            @PathVariable String contractType){
            Map<String, Object> map = new HashMap<String, Object>();
            List<AccountsReceivablePlan> accountsReceivablePlanList=null;
            int count=0;
            accountsReceivablePlanList= accountsReceivablePlanService.getRepository().findBySContractIdAndSContractType(contractId, contractType);
            count=accountsReceivablePlanList.size();
            map.put("data", accountsReceivablePlanList);
            map.put("draw", request.getParameter("draw"));
            map.put("recordsFiltered", count);
            map.put("recordsTotal", count);
            return map;
        }
    /**
     *  应收账计划数据
     * @param contractId
     * @param contractType
     * @return
     */
    @RequestMapping(value = "/{contractId}/{contractType}/getPlan", method = RequestMethod.GET)
    public Map<String, Object> getPlan (@PathVariable String contractId,
                                        @PathVariable String contractType){
        Map<String, Object> map = new HashMap<String, Object>();
        List<AccountsReceivablePlan> accountsReceivablePlanList=null;
        accountsReceivablePlanList= accountsReceivablePlanService.getRepository().findBySContractIdAndSContractType(contractId, contractType);
        map.put("data", accountsReceivablePlanList);
        return map;
    }
    /**
     *  应收账计划更新
     * @return
     */
    @RequestMapping(value = "/updata", method = RequestMethod.POST)
    public Map<String, Object> updataPlan (@RequestBody AccountsReceivablePlan accountsReceivablePlan){
        Map<String, Object> map = new HashMap<String, Object>();
        AccountsReceivableType sAccountsReceivableType = accountsReceivableTypeService.getRepository().findOne(accountsReceivablePlan.getsAccountsReceivableTypeId().getId());
        if(accountsReceivablePlan.getId() == ""){
        	accountsReceivablePlan.setId(java.util.UUID.randomUUID().toString());
        	accountsReceivablePlan.setCreateTime(new Date());
        	accountsReceivablePlan.setUpdateTime(new Date());
        	accountsReceivablePlan.setsAccountsReceivableTypeId(sAccountsReceivableType);
        	accountsReceivablePlanService.getRepository().save(accountsReceivablePlan);
        }else{
        	/*AccountsReceivablePlan OldAccountsReceivablePlan = accountsReceivablePlanService.getRepository().findOne(accountsReceivablePlan.getId());
        	OldAccountsReceivablePlan.setdAccountsReceivablePlanDate(accountsReceivablePlan.getdAccountsReceivablePlanDate());
        	OldAccountsReceivablePlan.setnTotalPrice(accountsReceivablePlan.getnTotalPrice());
        	OldAccountsReceivablePlan.setsContractId(accountsReceivablePlan.getsContractId());
        	OldAccountsReceivablePlan.setsContractType(accountsReceivablePlan.getsContractType());
        	OldAccountsReceivablePlan.setnTotalPrice(accountsReceivablePlan.getnTotalPrice());
        	OldAccountsReceivablePlan.setsMemo(accountsReceivablePlan.getsMemo());
        	OldAccountsReceivablePlan.setsAccountsReceivableTypeId(accountsReceivablePlan.getsAccountsReceivableTypeId());
        	OldAccountsReceivablePlan.setCreateTime(accountsReceivablePlan.getCreateTime());*/
        	accountsReceivablePlan.setsAccountsReceivableTypeId(sAccountsReceivableType);
        	accountsReceivablePlanService.getRepository().save(accountsReceivablePlan);
        }
        AaccountsReceivableAccorspandingContract aaccountsReceivableAccorspandingContract = aaccountsReceivableAccorspandingContractService.getRepository().findBySContractIdAndSContractTypeAndNContractOrgType(accountsReceivablePlan.getsContractId(), accountsReceivablePlan.getsContractType(), 0);
        if(aaccountsReceivableAccorspandingContract == null){
    		AaccountsReceivableAccorspandingContract newAaccountsReceivableAccorspandingContract = new AaccountsReceivableAccorspandingContract();
    		newAaccountsReceivableAccorspandingContract.setnContractOrgType(0);
    		newAaccountsReceivableAccorspandingContract.setnIsUpdate(0);
    		newAaccountsReceivableAccorspandingContract.setnIsUpdateForTotal(0);
    		newAaccountsReceivableAccorspandingContract.setsContractId(accountsReceivablePlan.getsContractId());
    		newAaccountsReceivableAccorspandingContract.setsContractType(accountsReceivablePlan.getsContractType());
    		aaccountsReceivableAccorspandingContractService.getRepository().save(newAaccountsReceivableAccorspandingContract);
    	}else{
    		aaccountsReceivableAccorspandingContract.setnContractOrgType(0);
    		aaccountsReceivableAccorspandingContract.setnIsUpdate(0);
    		aaccountsReceivableAccorspandingContract.setnIsUpdateForTotal(0);
    		aaccountsReceivableAccorspandingContract.setsContractId(accountsReceivablePlan.getsContractId());
    		aaccountsReceivableAccorspandingContract.setsContractType(accountsReceivablePlan.getsContractType());
    		aaccountsReceivableAccorspandingContractService.getRepository().save(aaccountsReceivableAccorspandingContract);
    	}
        Account a = this.getMyAccount();
        User user = a.getUser();
        //payPlanService.payNotionalPooling(accountsReceivablePlan.getsContractId(),user.getName());
        String contractId = accountsReceivablePlan.getsContractId();
        String contractType = accountsReceivablePlan.getsContractType();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        BigDecimal bigDecimal = new BigDecimal(accountsReceivablePlan.getnTotalPrice());
        String time = null;
        if(accountsReceivablePlan.getdAccountsReceivablePlanDate()!=null) time = formatter.format(accountsReceivablePlan.getdAccountsReceivablePlanDate());
        String content = "";
        if (contractType.equals("项目合同")){
			Contract old = contractService.getRepository().findOne(contractId);
			content = accountsReceivablePlan.getId() == "" ? "新增" : "编辑" + "应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】";
		}else if (contractType.equals("备件合同")){
			ContractPart old = contractService.getRepository2().findOne(contractId);
			content = accountsReceivablePlan.getId() == "" ? "新增" : "编辑" + "应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】";
		}else if (contractType.equals("备泵合同")){
			ContractPump old = contractService.getRepository3().findOne(contractId);
			content = accountsReceivablePlan.getId() == "" ? "新增" : "编辑" + "应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】";
		}else if (contractType.equals("维修合同")){
			ContractRepair old = contractService.getRepository4().findOne(contractId);
			content = accountsReceivablePlan.getId() == "" ? "新增" : "编辑" + "应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】";
		}
		operateLogService.log(user, "应收账" + accountsReceivablePlan.getId() == "" ? "新增" : "编辑", content);

        return map;
    }
    
    /**
     *  应收账计划删除
     * @return
     */
    @RequestMapping(value = "/delbyid/{contractId}/{contractType}/{planIds}", method = RequestMethod.GET)
    public Map<String, Object> delbyid (@PathVariable String contractId,
            @PathVariable String contractType, @PathVariable String planIds){
        Map<String, Object> map = new HashMap<String, Object>();
        Account a = this.getMyAccount();
        User user = a.getUser();
        String[] aplanIds = planIds.split(",");
        String ids = "";
        if(aplanIds.length > 0){
        	for(int i = 0; i < aplanIds.length; i++){
        		ids += "'" + aplanIds[i] + "',";
        	}
        	ids = ids.substring(0, ids.length()-1);
        }
        List<AccountsReceivablePlan> AccountsReceivablePlanList = accountsReceivablePlanService.findByIds(ids);
        String content = "";
        if(AccountsReceivablePlanList.size()>0){
        	for(AccountsReceivablePlan accountsReceivablePlan : AccountsReceivablePlanList){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                BigDecimal bigDecimal = new BigDecimal(accountsReceivablePlan.getnTotalPrice());
                String time = null;
                if(accountsReceivablePlan.getdAccountsReceivablePlanDate()!=null) time = formatter.format(accountsReceivablePlan.getdAccountsReceivablePlanDate());
                if (contractType.equals("项目合同")){
        			Contract old = contractService.getRepository().findOne(contractId);
        			content += "删除应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】;";
        		}else if (contractType.equals("备件合同")){
        			ContractPart old = contractService.getRepository2().findOne(contractId);
        			content += "删除应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】;";
        		}else if (contractType.equals("备泵合同")){
        			ContractPump old = contractService.getRepository3().findOne(contractId);
        			content += "删除应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】;";
        		}else if (contractType.equals("维修合同")){
        			ContractRepair old = contractService.getRepository4().findOne(contractId);
        			content += "删除应收账信息【"+"合同号:"+old.getSupplierCode()+",款项:"+accountsReceivablePlan.getsAccountsReceivableTypeId().getsAccountsReceivableTypeName()+",金额:"+bigDecimal.toString()+",时间:"+time+"】;";
        		}
            	accountsReceivablePlanService.getRepository().delete(accountsReceivablePlan.getId());
            }
            if(content != ""){
            	content = content.substring(0, content.length()-1);
            	content += ".";
            	operateLogService.log(user, "应收账删除", content);
            }
            AaccountsReceivableAccorspandingContract aaccountsReceivableAccorspandingContract = aaccountsReceivableAccorspandingContractService.getRepository().findBySContractIdAndSContractTypeAndNContractOrgType(contractId, contractType, 0);
            if(aaccountsReceivableAccorspandingContract == null){
        		AaccountsReceivableAccorspandingContract newAaccountsReceivableAccorspandingContract = new AaccountsReceivableAccorspandingContract();
        		newAaccountsReceivableAccorspandingContract.setnContractOrgType(0);
        		newAaccountsReceivableAccorspandingContract.setnIsUpdate(0);
        		newAaccountsReceivableAccorspandingContract.setnIsUpdateForTotal(0);
        		newAaccountsReceivableAccorspandingContract.setsContractId(contractId);
        		newAaccountsReceivableAccorspandingContract.setsContractType(contractType);
        		aaccountsReceivableAccorspandingContractService.getRepository().save(newAaccountsReceivableAccorspandingContract);
        	}else{
        		aaccountsReceivableAccorspandingContract.setnContractOrgType(0);
        		aaccountsReceivableAccorspandingContract.setnIsUpdate(0);
        		aaccountsReceivableAccorspandingContract.setnIsUpdateForTotal(0);
        		aaccountsReceivableAccorspandingContract.setsContractId(contractId);
        		aaccountsReceivableAccorspandingContract.setsContractType(contractType);
        		aaccountsReceivableAccorspandingContractService.getRepository().save(aaccountsReceivableAccorspandingContract);
        	}
        }
        //payPlanService.payNotionalPooling(accountsReceivablePlan.getsContractId(),user.getName());
        return map;
    }
    /**
     * 获取页面数据
     */
    @RequestMapping(value = "getpage", method = RequestMethod.GET)
    public Map<String, Object> getPage(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, String> condition = new HashMap<String, String>();
        int start = Integer.parseInt(request.getParameter("start"));
        int length = Integer.parseInt(request.getParameter("length"));
        String key = request.getParameter("key");
        Account a = this.getMyAccount();
        String userId = a.getUser().getId();
        String superior = a.getUser().getSaleArea().getSuperior();
        String areaName = a.getUser().getSaleArea().getAreaName();
        String name = "paySchedule";
        Module module = this.getPageModule(name);
        String dataFilter = module.getDataFilter();
        if (key == null) {
            key = "";
        }
        key = key.replaceAll("\\s+", "");
        if (userId == null) {
            userId = "";
        }
        if (superior == null) {
            superior = "";
        }
        if (areaName == null) {
            areaName = "";
        }
        if (dataFilter == null) {
            dataFilter = "";
        }
        condition.put("key", key);
        condition.put("userId", userId);
        condition.put("superior", superior);
        condition.put("areaName", areaName);
        condition.put("dataFilter", dataFilter);
        List<ContractInfo> contracts = contractService.getContractInfos(start, length, condition, null, null);
        long count = contractService.getContractInfosCount(condition);
        map.put("data", contracts);
        map.put("draw", request.getParameter("draw"));
        map.put("recordsFiltered", count);
        map.put("recordsTotal", count);
        return map;
    }
}